package nl.windgazer.arachne.components.formelements;

import nl.windgazer.arachne.pages.CaptchaImage;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.FieldValidatorSource;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.Request;

import com.joostschouten.common.service.catpcha.CaptchaService;

public class Captcha {
	
	@Inject
	private FieldValidatorSource fieldValidatorSource;
	
	@Inject
	private Messages messages;
	
	@Environmental
    private FormSupport formSupport;
	
	@Inject
	private PageRenderLinkSource pageRenderSource;
	
	@Inject
	private ComponentResources resources;
	
	@Property
	private String captchaValue;
	
	@SuppressWarnings("unused")
	@Property
	@Parameter(required = true)
	private String label;
	
	@Component(id = "captchaField", parameters = {"value=captchaValue",
													"label=prop:label",
													"validate=required,captcha"})
	private TextField captchaField;
	
	@Inject
	private Request request;

	@Inject
	private CaptchaService _cs;
	
	@SetupRender
	void setup() {
		FieldValidator<String> captchaVal = new CaptchaValidator(request, _cs);
	}
	
	public String getCapchaUrl() {
		Link link = pageRenderSource.createPageRenderLink(CaptchaImage.class);
		return link.toAbsoluteURI();
	}
	
	public class CaptchaValidator implements FieldValidator<String> {
		
		private Request request;
		
		private CaptchaService _cs;
		
		public CaptchaValidator(Request request, CaptchaService captchaService) {
			this.request = request;
			_cs = captchaService;
		}

		public boolean isRequired() {
			return true;
		}

		public void render(MarkupWriter arg0) {
			//nothing for now
		}

		public void validate(String arg0) throws ValidationException {
			String captchaId = (String) request.getSession(true).getAttribute(CaptchaImage.CAPTCHA_ID_KEY);
			boolean validated = false;
			if(captchaId != null) {
				validated = _cs.validateCaptcha(captchaId, captchaValue);
			}
			if(!validated) {
				throw new ValidationException(messages.get("components.formelements.Captcha.validationFailed"));
			}
			
		}
		
	}

}
